<#import "../tpl/pageTep.ftl" as page>
<@page.pageBase currentMenu="商品管理">
<style>
    .button-large {
        font-size: 16px;
    }

    .webuploader-pick {
        background: none;
        padding: 0;
    }
</style>
<div class="xm-product">
    <div class="row">
        <div class="panel">
            <div class="panel-header">
                <a href="${basepath}/rest/manage/product/toList">返回上一级</a>
            </div>
            <div class="panel-body">
                <form id="editForm" class="form-horizontal" action="${basepath}/rest/manage/product/updateProductJson"
                      method="post">
                    <input type="hidden" class="control-text span-width span10" name="id" value="${e.id!}">

                    <div class="control-group">
                        <label class="control-label">
                            <s>*</s>
                            商品名称：
                        </label>

                        <div class="controls">
                            <input type="text" class="control-text span-width span10" name="name" placeholder="请输入商品名称"
                                   value="${e.name!}" data-rules="{required : true}">
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="time-label control-label">商品从属：</label>
                        <div class="time-controls controls">
                            <select name="type" class="input-normal" id="status"  value="${e.type!}">
                                <option value="1">零售</option>
                                <option value="2">批发</option>
                            </select>
                        </div>
                    </div>
                    <div class="control-group catalog hide">
                        <label class="control-label">
                            商品类别：
                        </label>
                        <div class="controls">
                            <div id="sub-catalog">
                                <input type="hidden" id="sub-value" name="catalogID" value=${e.catalogID!}>
                            </div>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">
                            <s>*</s>
                            商品主图：
                        </label>

                        <div class="controls" style="height: auto">
                            <input type="hidden" name="picture" value="${e.picture}"/>
                            <img id="mainPicture" src="${basepath}/${e.picture}"
                                 style="max-width: 250px;width: 100%;max-height: 250px;">
                            <a id="pictureBtn" class="button button-min button-primary pull-right hidden"
                               style="height:20px;margin-left: 10px;">上传</a>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">
                            <s>*</s>
                            商品封面：
                        </label>
                        <div class="controls" style="height: auto">
                            <input type="hidden" name="cover" value="${e.cover}"/>
                            <img id="coverPicture" src="${basepath}/${e.cover}"
                                 style="max-width: 250px;width: 100%;max-height: 250px;">
                            <a id="coverBtn" class="button button-min button-primary pull-right hidden"
                               style="height:20px;margin-left: 10px;">上传</a>
                        </div>
                    </div>
                    <br/>
                    <div class="control-group">
                        <label class="control-label">
                            <s>*</s>
                            商品详情：
                        </label>

                        <div class="controls control-row4" style="height: 350px;">
                            <textarea type="text" class="input-large" data-rules="{required:true}" name="introduce"
                                      id="productHTML">${e.introduce!}</textarea>
                        </div>
                    </div>
                    <h3 class="offset2">商品图片
                        <a class="button button-primary pull-right" id="imagesBtn" style="height:20px">新增图片</a>
                    </h3>
                    <hr>
                    <input type="hidden" class="control-text span-width " name="images" id="productImgs"
                           value="${e.images!}"
                           data-rules="{required:true}">

                    <div id="imagesGrid" class="xm-grid">
                    </div>
                <#----------------------------------------------------商品规格------------------------------------->
                    <div id="specList">
                        <h3 class="offset2">商品规格
                            <a class="button button-primary pull-right" href="javascript:addSpec()">新增规格</a>
                        </h3>
                        <hr>
                        <input type="hidden" class="picture1 control-text span-width " name="combination"
                               data-rules="{required:true}" id="combination">
                        <input type="hidden" class="picture1 control-text span-width " name="price"
                               id="price" >
                        <input type="hidden" class="picture1 control-text span-width " name="cost"
                               id="cost" >
                        <input type="hidden" class="picture1 control-text span-width " name="stock"
                               id="stock" >
                        <div id="specGrid" class="xm-grid">
                        </div>
                    </div>
                    <div class="centered">
                        <button type="submit" class="button  button-large  button-success">立即上架</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<#-----------------------------------------------添加商品规格 start------------------------------------------->
<div id="addSpecContent" style="display:none;">
    <form id="addSpecForm" class="form-horizontal" >
        <div class="row">
            <div class="control-group span16">
                <label class="control-label">规格组合：</label>

                <div class="controls">
                    <input type="text" class="input-normal control-text" name="combination" id="addCombination"
                           data-rules="{required : true}"/>
                </div>
            </div>
            <div class="control-group span16">
                <label class="control-label">售价：</label>

                <div class="controls">
                    <input type="text" class="input-normal control-text" name="price" id="addPrice"
                           data-rules="{required : true,number:true}"/>
                </div>
            </div>
            <div class="control-group span16">
                <label class="control-label">进价：</label>

                <div class="controls">
                    <input type="text" class="input-normal control-text" name="cost" id="addCost"
                           data-rules="{required : true,number:true}"/>
                </div>
            </div>
            <div class="control-group span16">
                <label class="control-label">库存：</label>

                <div class="controls">
                    <input type="text" class="input-normal control-text" name="stock" id="addStock"
                           data-rules="{required : true,number:true}"/>
                </div>
            </div>
        </div>
    </form>
</div>
<#-----------------------------------------------添加商品规格end------------------------------------------->
<#-----------------------------------------------编辑商品规格start------------------------------------------->
<div id="editSpecContent" style="display:none;">
    <form id="editSpecForm" class="form-horizontal">
        <div class="row">
            <div class="control-group span16">
                <label class="control-label">规格组合：</label>

                <div class="controls">
                    <input type="text" class="input-normal control-text" name="combination" id="editCombination"
                           data-rules="{required : true}"/>
                </div>
            </div>
            <div class="control-group span16">
                <label class="control-label">原价：</label>

                <div class="controls">
                    <input type="text" class="input-normal control-text" name="cost" id="editCost"
                           data-rules="{required : true,number:true}"/>
                </div>
            </div>
            <div class="control-group span16">
                <label class="control-label">售价：</label>

                <div class="controls">
                    <input type="text" class="input-normal control-text" name="price" id="editPrice"
                           data-rules="{required : true,number:true}"/>
                </div>
            </div>
            <div class="control-group span16">
                <label class="control-label">库存：</label>

                <div class="controls">
                    <input type="text" class="input-normal control-text" name="stock" id="editStock"
                           data-rules="{required : true,number:true}"/>
                </div>
            </div>
        </div>
    </form>
</div>
<#-----------------------------------------------编辑商品规格end------------------------------------------->

<#-----------------------------------------------编辑商品规格end------------------------------------------->

<script type="text/javascript">
    var editor = UE.getEditor('productHTML');
    var Grid = BUI.Grid;
    var Store = BUI.Data.Store;
    var Data = BUI.Data;
    var Select = BUI.Select;
    <#-----------------------------商品分类 start---------------------------->
    //一级商品目录下拉
    var pStore = new Store({
        url: '${basepath}/rest/manage/catalog/getParentCatalog',
        autoLoad: true,
        root: 'data'
    });
    var sSelect = new Select.Select({
        render: '#p-catalog',
        valueField: '#p-value',
        list: {
            itemTpl: '<li >{name}</li>',
            idField: 'name'
        },
        store: pStore
    }).render();

    var subStore = new Store({
        url: '/rest/manage/catalog/getCatalog',  //设置加载数据的URL
        autoLoad: true, //创建Store时自动加载数据
        proxy: {
            method: 'GET',
            dataType: 'json'
        },
        root: 'data'
    });
    var subSelect = new Select.Select({
        render: '#sub-catalog',
        valueField: '#sub-value',
        list: {
            itemTpl: '<li>{name}</li>',
            idField: 'id'
        },
        store: subStore
    });
    subSelect.render();
    //获取二级下拉数据源
    sSelect.on('change', function (e) {
        var id = e.item.id;
        var obj = new Object();
        obj.pid = id;
        subStore.load(obj);       //接收对象参数
    });
    <#-----------------------------商品分类 end----------------------------->
    var imagesStore = new Store({});
    <#-----------------------------商品图片编辑 start----------------------------->
    var pictureUploader = WebUploader.create({
        auto: true,
        swf: '${staticpath}/common/ueditor/third-party/webuploader/Uploader.swf',
        server: '${basepath}/rest/manage/ued/config?action=uploadimage',
        pick: '#pictureBtn',
        resize: false,
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png,'
        }
    });

    pictureUploader.on('uploadSuccess', function (file, response) {
        pictureUploader.removeFile(file);
        editForm.setFieldValue("picture", response.url);
        $("#mainPicture").attr("src", "${basepath}/" + response.url);
    });
    var coverUploader = WebUploader.create({
        auto: true,
        swf: '${staticpath}/common/ueditor/third-party/webuploader/Uploader.swf',
        server: '${basepath}/rest/manage/ued/config?action=uploadimage',
        pick: '#coverBtn',
        resize: false,
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png,'
        }
    });

    coverUploader.on('uploadSuccess', function (file, response) {
        pictureUploader.removeFile(file);
        editForm.setFieldValue("cover", response.url);
        console.log(response.url);
        $("#coverPicture").attr("src", "${basepath}/" + response.url);
    });
    /*--------------------------商品图片列表  begin--------------------*/
    /**
     * 图片信息
     * @type {*[]}
     */

    var imagesColumns = [
        {
            title: '图片', dataIndex: 'url', width: '30%', elCls: "center", renderer: function (data) {
            return '<img src="${basepath}/' + data + '" width="100px" height="100px"/>'
        }
        },
        {
            title: '状态', dataIndex: 'state', width: '30%', elCls: "center", renderer: function (data) {
            if (data == "SUCCESS") {
                return "上传成功";
            }
            return "上传失败";
        }
        },
        {
            title: '操作', dataIndex: 'title', width: '40%', elCls: "center", renderer: function (data, obj, index) {
                return '<a href="javascript:delImages(' + obj.id + ')">删除</a>';
        }
        }
    ];
    /**
     * 删除缓存图片信息
     * @param index
     */
    function delImages(index) {
        var record = imagesStore.find('id',index);
        imagesStore.remove(record);
        var imgStr = imagesStore.getResult();
        var imgArr = new Array();
        for (var i = 0; i < imgStr.length; i++) {
            imgArr[i] = imgStr[i].url
        }
        $("#productImgs").val(imgArr.join(","));
    }
    /**
     * 初始化图片列表数据源
     * */
    function initImagesStore() {
        var imgArr = $("#productImgs").val().split(',');
        for (var i = 0; i < imgArr.length; i++) {
            var obj = new Object();
            obj.id=i;
            obj.url = imgArr[i];
            obj.state = "SUCCESS";
            imagesStore.add(obj);
        }
    }

    initImagesStore();
    var imagesGrid = new Grid.Grid({
        render: '#imagesGrid',
        width: '100%',//如果表格使用百分比，这个属性一定要设置
        columns: imagesColumns,
        idField: 'title',
        store: imagesStore
    }).render();
    /*--------------------------活动图片列表  end--------------------*/

    /*------------------------图片上传插件配置  begin-----------------------*/
    var uploader = WebUploader.create({
        auto: true,
        swf: '${staticpath}/ueditor/third-party/webuploader/Uploader.swf',
        server: '${basepath}/rest/manage/ued/config?action=uploadimage',
        pick: '#imagesBtn',
        resize: false,
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png,'
        }
    });

    uploader.on('uploadSuccess', function (file, response) {
        uploader.removeFile(file);
        var imgs = imagesStore.getResult();
        if (imgs.length > 2) {
            BUI.Message.Alert('不能多于三张图片', function () {
            }, 'info');
        } else {
            imagesStore.add(response);
            var imgArr = new Array();
            for (var i = 0; i < imgs.length; i++) {
                imgArr[i] = imgs[i].url;
            }
            $("#productImgs").val(imgArr.join(","));
            imagesStore.add(obj);
        }
    });
    /*--------------------------商品图片列表  end--------------------*/
    <#-----------------------------商品图片编辑 end----------------------------->
    <#-----------------------------商品编辑保存跳转 start----------------------------->
    var editForm = new BUI.Form.Form({
        srcNode: '#editForm',
        submitType: 'ajax',
        callback: function (data) {
            if (editForm.isValid()) {
                if (data.success) {
                    window.location.href = "${basepath}/rest/manage/product/toList";
                } else {
                    BUI.Message.Alert("上架失败", 'error');
                }
            } else {
                editForm.valid();
            }
        }
    }).render();
    <#-----------------------------商品编辑保存跳转 end----------------------------->

    /*--------------------------产品规格列表  begin--------------------*/
    /**
     * 规格信息
     * @type {*[]}
     */
    $('select').change(function () {
        state=$(this).val()==1?'零售价':'批发价';
    })
    var state='售价';

    var specColumns = [
        {title: '规格组合', dataIndex: 'combination', elCls: "center"},
        {title: '原价', dataIndex: 'cost', elCls: "center"},
        {title: '售价', dataIndex: 'price', elCls: "center" ,id:1},
        {title: '库存', dataIndex: 'stock', elCls: "center"},
        {
            title: '操作', dataIndex: 'id', elCls: "center", renderer: function (data) {
            return '<a href="javascript: editProduct(\'' + data + '\')">编辑</a>' +
                    '<a style="margin-left:10px;"  href="javascript:delProduct(\'' + data + '\')">删除</a>';
        }
        }
    ];

    var specStore = new Store({
        url: '/rest/manage/spec/getSpec?productID=' +${e.id},
        autoLoad: true, //自动加载数据
        params: { //配置初始请求的参数
            length: '10',
            status: $("#status").val()
        },
        pageSize: 10,    // 配置分页数目
        root: 'list',
        totalProperty: 'total'
    });
    var specGrid = new Grid.Grid({
        render: '#specGrid',
        columns: specColumns,
        plugins: [Grid.Plugins.CheckSelection],
        forceFit: true,
        loadMask: true, //加载数据时显示屏蔽层
        store: specStore
    }).render();
    /**
     * 初始化商品信息列表数据源
     * */

    $.ajax({
        type: "GET",
        url: "/rest/manage/spec/getSpec",
        data: {
            productID: ${e.id}
        },
        dataType: "json",
        success: function (data) {
            var combinationArr="",
                    priceArr="",
                    costArr="",
                    stockArr="";
            $.each(data.list, function (i, o) {
                combinationArr += o.combination + ";";
                priceArr+= o.price + ";";
                costArr+= o.cost + ";";
                stockArr+= o.stock + ";";

            });
            $("#combination").val(combinationArr);
            $("#price").val(priceArr);
            $("#cost").val(costArr);
            $("#stock").val(stockArr);
        }

    });
    /**
     * 删除缓存商品信息
     * @param index
     */
    function delProduct(index) {
        //remove行数
        var record = specStore.find('id',index);
        specStore.remove(record);
        var imgStr = specStore.getResult();
        var combinationArr  = new Array();
        var priceArr = new Array();
        var costArr = new Array();
        var stockArr = new Array();
        for (var i = 0; i < imgStr.length; i++) {
            combinationArr[i] = imgStr[i].combination;
            priceArr[i] = imgStr[i].price;
            costArr[i] = imgStr[i].cost;
            stockArr[i] = imgStr[i].stock;
        }
        $("#combination").val(combinationArr.join(";"));
        $("#price").val(priceArr.join(";"));
        $("#cost").val(costArr.join(";"));
        $("#stock").val(stockArr.join(";"));
    }
    /*--------------------------产品规格列表  end---------------------------*/

    /*----------------------------------------------新增规格表单处理 begin------------------------------------*/
    var addSpecForm = new BUI.Form.Form({
        srcNode: '#addSpecForm',
        submitType: 'ajax',
        callback: function (data) {
            var obj = new Object();
            obj.start = 0; //返回第一页
            specStore.load(obj);
            addSpcDialog.close();
        }
    }).render();

    var addSpcDialog = new BUI.Overlay.Dialog({
        title: '新增规格',
        width: 500,
        height: 320,
        contentId: 'addSpecContent',
        success: function () {
            this.close();
            if (addSpecForm.isValid()) {
                var stores=specStore.getResult();
                var obj = new Object();
                var i=0;
                if(stores==null||stores==""){
                    obj.id=i;
                }else{
                    obj.id=stores[stores.length-1].id+1;
                }
                obj.combination = $('#addCombination').val();
                obj.price = $('#addPrice').val();
                obj.cost = $('#addCost').val();
                obj.stock = $('#addStock').val();
                specStore.add(obj);
                var addCombination = $('#addCombination').val();
                var addPrice = $('#addPrice').val();
                var addCost = $('#addCost').val();
                var addStock = $('#addStock').val();
                var inputCombination = $("#combination").val();
                var inputPrice = $("#price").val();
                var inputCost = $("#cost").val();
                var inputStock = $("#stock").val();
                if(inputCombination!=""&&inputPrice!=""&&inputCost!=""&&inputStock!=""){
                    $("#combination").val(inputCombination + '' + addCombination);
                    $("#price").val(inputPrice + '' + addPrice);
                    $("#cost").val(inputCost + '' + addCost);
                    $("#stock").val(inputStock + '' + addStock);
                }else {
                    $("#combination").val(addCombination);
                    $("#price").val(addPrice);
                    $("#cost").val(addCost);
                    $("#stock").val(addStock);
                }
            } else {
                addSpecForm.valid();
            }
        }
    });
    function addSpec() {
        $('#addCombination').val("");
        $('#addPrice').val("");
        $('#addCost').val("");
        $('#addStock').val("");
        addSpecForm.clearErrors();
        addSpecForm.clearFields();
        addSpcDialog.show();
    }
    /*----------------------------------------------新增规格表单处理 end------------------------------------*/
    /*------------------------------------------------编辑规格表单处理 start-----------------------------------------------*/
    var editSpecForm = new BUI.Form.Form({
        srcNode: '#editSpecForm',
        submitType: 'ajax',
        callback: function (data) {
            var obj = new Object();
            obj.start = 0; //返回第一页
            specStore.load(obj);
            editSpecDialog.close();
        }
    }).render();
    var editRecord = new Object();
    function editProduct(index) {
        editRecord = specStore.find('id',index);
        editSpecDialog.show();
        $('#editCombination').val(editRecord.combination);
        $('#editPrice').val( editRecord.price);
        $('#editCost').val( editRecord.cost);
        $('#editStock').val( editRecord.stock);
    }
    var editSpecDialog = new BUI.Overlay.Dialog({
        title: '编辑商品规格',
        width: 500,
        height: 320,
        contentId: 'editSpecContent',
        success: function () {
            this.close();
            if (editSpecForm.isValid()) {
                editRecord.combination = $('#editCombination').val();
                editRecord.price = $('#editPrice').val();
                editRecord.cost = $('#editCost').val();
                editRecord.stock = $('#editStock').val();
                specStore.update(editRecord);
                var productStr = specStore.getResult();
                var editCombination='';
                var editPrice='';
                var editCost='';
                var editStock='';
                for (var i = 0; i < productStr.length; i++) {
                    editCombination=editCombination+';'+productStr[i].combination;
                    editPrice=editPrice+';'+productStr[i].price;
                    editCost=editCost+';'+productStr[i].cost;
                    editStock=editStock+';'+productStr[i].stock;
                }
                $("#combination").val(editCombination.substr(1));
                $("#price").val(editPrice.substr(1));
                $("#cost").val(editCost.substr(1));
                $("#stock").val(editStock.substr(1));

            } else {
                editSpecForm.valid();
            }
        }
    });
    /*------------------------------------------------编辑规格表单处理 end------------------------------------------------*/

    /*----------------------------------------------新增参数表单处理 begin------------------------------------*/
    var addNatureForm = new BUI.Form.Form({
        srcNode: '#addNatureForm',
        submitType: 'ajax',
        callback: function (data) {
            var obj = new Object();
            obj.start = 0; //返回第一页
            natureStore.load(obj);
            addNatureDialog.close();
        }
    }).render();

    var addNatureDialog = new BUI.Overlay.Dialog({
        title: '新增参数',
        width: 500,
        height: 200,
        contentId: 'addNatureContent',
        success: function () {
            if (addNatureForm.isValid()) {
                addNatureForm.submit();
            } else {
                addNatureForm.valid();
            }
        }
    });
    function addNature() {
        addNatureForm.clearErrors();
        addNatureForm.clearFields();
        addNatureDialog.show();
    }
    /*----------------------------------------------新增参数表单处理 end------------------------------------*/
    /*------------------------------------------------编辑参数表单处理 start-----------------------------------------------*/
    var editNatureForm = new BUI.Form.Form({
        srcNode: '#editNatureForm',
        submitType: 'ajax',
        callback: function (data) {
            var obj = new Object();
            obj.start = 0; //返回第一页
            natureStore.load(obj);
            editNatureDialog.close();
        }
    }).render();

    var editNatureDialog = new BUI.Overlay.Dialog({
        title: '编辑商品参数',
        width: 500,
        height: 200,
        contentId: 'editNatureContent',
        success: function () {
            if (editNatureForm.isValid()) {
                editNatureForm.submit();
            } else {
                editNatureForm.valid();
            }
        }
    });

    //编辑按钮事件
    function editNature(id) {
        $.ajax({
            type: "POST",
            dataType: "json",
            url: "/rest/manage/nature/toEditJson",//弹窗编辑
            data: {
                id: id
            },
            success: function (data) {
                var form = $("#editNatureForm")[0];
                BUI.FormHelper.setFields(form, data.data);
                natureStore.load();
                editNatureDialog.show();
            }
        });
    }
    /*------------------------------------------------编辑参数表单处理 end------------------------------------------------*/


    /*--------------------删除规格操作----------------------------*/
    function delSpec(com) {
        BUI.Message.Confirm('确认要删除吗？', function () {
            $.ajax({
                type: "POST",
                url: "${basepath}/rest/manage/spec/deleteByComJson",
                dataType: "json",
                data: {
                    combination: com
                },
                success: function (data) {
                    var obj = new Object();
                    obj.start = 0; //返回第一页
                    specStore.load(obj);
                }
            });
        }, 'question');
    }

    /*--------------------删除参数操作----------------------------*/
    function delNature(name) {
        BUI.Message.Confirm('确认要删除吗？', function () {
            $.ajax({
                type: "POST",
                url: "${basepath}/rest/manage/nature/deleteByNameJson",
                dataType: "json",
                data: {
                    name: name
                },
                success: function (data) {
                    var obj = new Object();
                    obj.start = 0; //返回第一页
                    natureStore.load(obj);
                }
            });
        }, 'question');
    }
    if(${e.catalogID!}&&${e.catalogID!}!=0){
        console.log(${e.catalogID!});
        $('.catalog').show()
    }
    $('#status').change(function () {
        if($(this).val()==2){
            $('.catalog').find('input').val(0).end().hide()
        }else{
            $('.catalog').find('input').val('').end().show()
        }
    });
    /*------------------商品规格编辑 end-------------------------------*/

</script>
</@page.pageBase>
